package gov.decea.projects.sgq.controllers;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import com.future.projects.imobiliaria.forms.UsuarioFormBean;
import gov.decea.projects.sgq.api.MainService;
import gov.decea.projects.sgq.core.exception.CoreException;
import gov.decea.projects.sgq.model.Usuario;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 *
 * @author dctp
 */
@Controller
@RequestMapping("/usuarios")
public class UsuariosController {

    private final MainService mainService;

    @Autowired
    public UsuariosController(MainService mainService) {
        this.mainService = mainService;
    }

    @RequestMapping({"/", "/index", ""})
    public String index(Model model, WebRequest request) {

        List<Map<Object, Object>> dataList = new ArrayList<Map<Object, Object>>();

       // List<Usuario> usuarios = mainService.listUsuarios();

//        for (Usuario usuario : usuarios) {
//            Map<Object, Object> item = new HashMap<Object, Object>();
//            item.put("id", usuario.getId());
//            item.put("nome", usuario.getNome());
//            item.put("login", usuario.getLogin());
//            dataList.add(item);
//        }

        model.addAttribute("total", dataList.size());
        model.addAttribute("dataList", dataList);

        return "usuarios";
    }

    @RequestMapping("/new")
    public String newUsuario(Model model) {

        UsuarioFormBean form = new UsuarioFormBean();
        model.addAttribute(form);
        return "usuarios/form";
    }

    @RequestMapping("/edit")
    public String editUsuario(Model model, WebRequest request) {
        UsuarioFormBean form = new UsuarioFormBean();
        String idParam = request.getParameter("id");
        if (idParam == null) {
            return "redirect:index";
        }
        Long id = Long.parseLong(idParam);

//        Usuario usuario = mainService.findUsuario(id);
//        form.setId(usuario.getId());
//        form.setLogin(usuario.getLogin());
//        form.setNome(usuario.getNome());
//        form.setPassword(usuario.getPassword());
        // PREENCHER FORMULÁRIO COM ID INCLUSIVE
        model.addAttribute(form);
        return "usuarios/form";
    }

    @RequestMapping("/save")
    public String saveUsuario(Model model, @Valid UsuarioFormBean usuarioFormBean,
            BindingResult bindingResult, WebRequest request) {

        if (bindingResult.hasErrors()) {
            return "usuarios/form";
        }

        Usuario usuario = new Usuario();
        usuario.setId(usuarioFormBean.getId());
        usuario.setNome(usuarioFormBean.getNome());
        usuario.setLogin(usuarioFormBean.getLogin());
        usuario.setPassword(usuarioFormBean.getPassword());

        try {
            if (usuario.getId() == null) {
                //Long id = mainService.createUsuario(usuario);
                //usuario.setId(id);
                model.addAttribute("successMessage", "Usuário criado com sucesso!");
            } else {
                //mainService.updateUsuario(usuario);
                model.addAttribute("successMessage", "Usuário atualizado com sucesso!");
            }

        } catch (CoreException ex) {
            model.addAttribute("errorMessage", ex.getMessage());
            return "usuarios/form";
        }

        Map<Object, Object> data = new HashMap<Object, Object>();
        data.put("nome", usuario.getNome());
        data.put("id", usuario.getId());
        data.put("login", usuario.getLogin());

        model.addAttribute("data", data);

        return "usuarios/detail";

    }

    @RequestMapping("/detail")
    public String detailUsuario(Model model, WebRequest request) {
        Map<Object, Object> data = new HashMap<Object, Object>();
        String idParam = request.getParameter("id");
        if (idParam == null) {
            return "redirect:index";
        }
        Long id = Long.parseLong(idParam);
        //Usuario usuario = mainService.findUsuario(id);

//        data.put("login", usuario.getLogin());
//        data.put("id", usuario.getId());
//        data.put("nome", usuario.getNome());

        model.addAttribute("data", data);
        return "usuarios/detail";
    }

    @RequestMapping("/remove")
    public String removeUsuario(Model model, WebRequest request,
            final RedirectAttributes redirectAttributes) {
        Map<Object, Object> data = new HashMap<Object, Object>();
        String idParam = request.getParameter("id");
        if (idParam == null) {
            return "redirect:index";
        }
        Long id = Long.parseLong(idParam);

        try {
           // mainService.removeUsuario(id);
            redirectAttributes.addFlashAttribute("successMessage", "Usuário foi removido com sucesso!");
            
        } catch (CoreException ex) {
            redirectAttributes.addFlashAttribute("errorMessage", ex.getMessage());
            return "redirect:index";
        }

        return "redirect:index";
    }
}
